package com.example.ddz.framework.impl;

/**
 * Created by IntelliJ IDEA.
 * User: Marcel Melzig
 * Date: 20.07.11
 * Time: 20:32
 */

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;

import com.example.ddz.framework.IAudio;
import com.example.ddz.framework.IMusic;
import com.example.ddz.framework.ISound;

/**
 * The class implements the IAudio interface and should be used to handle all kinds of audio files.
 */
public class Audio implements IAudio
{
    private final AssetManager assets;
    private final SoundPool soundPool;

    /**
     * Instantiates an instance of the Audio class. The Audio class handles all kinds of music and sounds.
     *
     * @param activity The activity which defines the main application.
     */
    public Audio(Activity activity)
    {
        activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        this.assets = activity.getAssets();
        this.soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
    }

    /**
     * Creates an instance of a class which implements the IMusic interface.
     *
     * @param filename The path to a music file.
     * @return An IMusic instance in form of a Music object.
     */
    @Override
    public IMusic NewMusic(String filename)
    {
        try
        {
            AssetFileDescriptor assetDescriptor = assets.openFd(filename);
            return new Music(assetDescriptor);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Couldn't load music '" + filename + "'");
        }
    }

    /**
     * Creates an instance of a class which implements the ISound interface.
     *
     * @param filename The path to a sound instance.
     * @return An ISound instance in form of a Sound object.
     */
    @Override
    public ISound NewSound(String filename)
    {
        try
        {
            AssetFileDescriptor assetDescriptor = assets.openFd(filename);
            int soundId = soundPool.load(assetDescriptor, 0);
            return new Sound(soundPool, soundId);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Couldn't load sound '" + filename + "'");
        }
    }
}
